using AutoMapper;
using Domain.Material_Management;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.Material_Management;
using MES.Server.API.Dto.Material_Management.OutPut;
using ReturnValue;

namespace MES.Server.API.Application.Handler.Material_Management
{
    public class GetBomHandler : IRequestHandler<GetBomCommand, ApiPaging<GetBomOutPut>>
    {
        private readonly IRepository<BomModel> bomRepo;
        private readonly IMapper mapper;

        public GetBomHandler(IRepository<BomModel> bomRepo, IMapper mapper)
        {
            this.bomRepo = bomRepo;
            this.mapper = mapper;
        }

        /// <summary>
        /// 获取BOM列表（分页）
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiPaging<GetBomOutPut>> Handle(GetBomCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiPaging<GetBomOutPut>();

            var query = bomRepo.GetAll().Where(a => !a.IsDel).OrderBy(a => a.CreateTime);
            
            result.Totalcount = query.Count();
            var data = query.OrderByDescending(x => x.CreateTime).Skip((request.PageIndex - 1) * request.PageSize)
                           .Take(request.PageSize)
                           .ToList();

            result.TotalPage = mapper.Map<List<GetBomOutPut>>(data);
            result.Message = "获取BOM列表成功";
           result.Code =StatusCode.Success;

            return await Task.FromResult(result);
        }
    }
}
